<?php

class Index 
{
    // 查看商品数量
    public function getproducts(){
        $products = Db::table("products")->find(["id" => 1]);
    }

    // 下单扣库存
    public function reduce_stock(){
        Db::table("products")->startTrans();

        try{
            $products = Db::table("products")->find(["id" => 1]);

            if($products['store']>0){
                $products['store'] = $products['store'] - 1;

                Db::table("products")->update($products);

                echo '秒杀成功';

            }else{
                echo '秒杀结束';
            }

            Db::table("products")->commit();
        } catch (Exception $e){
            Db::table("products")->rollback();
            echo $e->getMessage();
        }
        echo '<br/>';
        var_dump($products);
    }

    // 商品加入队列
    public function add_queue(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        $store = 10;
        $len = $store - $redis->Lsize("goods_nums");

        for($i = 0; $i < $len; $i++){
            $redis->lpush("goods_nums",microtime());
        }

        $products = $redis->lRange("goods_nums",0,-1);

        var_dump($products);
    }

    // 商品出队列
    public function delete_queue(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        $len = $redis->Lsize("goods_nums");

        if($len > 0){
            $arr = $redis->rPop("goods_nums");

            $products = Db::table("products")->find(["id" => 1]);

            var_dump($products['store']);
            if($products['store']>0){
                $products['store'] = $products['store'] - 1;

                Db::table("products")->update($products);

                echo '秒杀成功';
            }else{
                echo '秒杀结束1';
            }
        }else{
            echo '秒杀结束';
        }

    }
}